package com.gombe.credit.app.ui.fragment

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.gombe.credit.app.R
import com.gombe.credit.app.common.CommonFragment
import com.gombe.credit.app.configs.GombeCreditApiPath
import com.gombe.credit.app.configs.GombeCreditApiUrl
import com.gombe.credit.app.configs.GombeCreditApiUrl.addCommonParams
import com.gombe.credit.app.databinding.FragmentGombeCreditHomeBinding
import com.gombe.credit.app.event.GombeCreditEventData
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.event.room.GombeCreditPointManager
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.ui.activity.ActGombeCreditApply
import com.gombe.credit.app.ui.activity.ActGombeCreditPermissions
import com.gombe.credit.app.ui.activity.ActGombeCreditProcessSteps
import com.gombe.credit.app.ui.dialog.DilaogGombeCreditLimitIncreased
import com.gombe.credit.app.utils.GombeCreditDensityUtil
import com.gombe.credit.app.utils.GombeCreditTitleBarUtil
import com.gombe.credit.app.utils.helper.GombeCreditProcessHelper
import com.gombe.credit.app.utils.log.GombeCreditLogger
import com.gombe.credit.app.utils.shared.GombeCreditSharedHelper
import com.gombe.credit.app.utils.shared.GombeCreditSharedKey
import com.gombe.credit.lib.adapter.GombeCreditOnSingleClickListener
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions
import java.math.BigDecimal

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：主页
 */
class FragmentGombeCreditHome : CommonFragment() {
    private var _binding: FragmentGombeCreditHomeBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "gombe credit home binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var limitData: JSONObject? = null

    override fun takeGombeCreditRootView(inflater: LayoutInflater): View {
        _binding = FragmentGombeCreditHomeBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        _binding?.homeTitleBarLayout?.setPadding(0, GombeCreditTitleBarUtil.getStatusBarHeight()+GombeCreditDensityUtil.dp2px(10f), 0, 0)
        _binding?.homePageRefreshLayout?.setColorSchemeResources(R.color.theme, R.color.black)
    }

    override fun initGombeCreditListener() {
        _binding?.imgCustomer?.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                showCustomerDialog("Home Page")
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER,"Home Page")
            }
        })
        _binding?.homePageRefreshLayout?.setOnRefreshListener {
            onGombeCreditRefreshData()
        }
        _binding?.btnApplyNow?.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.LOAN_APPLY,"Home Page")
                // TODO: 首页点申请 需上报所有埋点
                GombeCreditPointManager.getInstance().manualReport()

                checkGombeCreditPermissions()
            }
        })
    }

    override fun takeGombeCreditData() {
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.HOME_START)
    }

    /**
     * 刷新流程
     */
    private fun onGombeCreditRefreshData(){
        publishEventData(GombeCreditEventData(GombeCreditEventData.TYPE.GOMBECREDIT_PROCESS_REFRESH))
    }

    /**
     * 显示额度
     */
    private fun showGombeCreditHomeLimit(data: JSONObject?){
        limitData = data
        data?.let {
            _binding?.textHomeCurrency?.text = it.optString("currency")
            _binding?.textHomeLimit?.text = BigDecimal(it.optString("amount")).stripTrailingZeros().toPlainString()
        }
    }

    /**
     * 权限声明列表
     */
    private val permissionResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                var isNext = false
                result.data?.let { bundle ->
                    val isAgree = bundle.getBooleanExtra("isPermissionAgree",false)
                    GombeCreditLogger.e(">>>>>>>>>permission is agree ：$isAgree")
                    //同意，校验权限 进行下一步
                    isNext = if (isAgree){
                        true
                    } else {//拒绝，
                        //是否是广告渠道
                        val isAdSource = GombeCreditSharedHelper.takeGombeCreditSharedBoolean(GombeCreditSharedKey.GOMBECREDIT_IS_ADSOURCE)
                        //非广告渠道才继续校验进行下一步
                        !isAdSource
                    }
                }
                if (isNext){
                    checkGombeCreditPermissions()
                }
            }
        }
    }

    /**
     * 检查权限
     */
    private fun checkGombeCreditPermissions(){
        //权限页操作状态 : 0未操作  1已同意  -1拒绝
        val permissionStatus = GombeCreditSharedHelper.takeGombeCreditSharedInt(GombeCreditSharedKey.GOMBECREDIT_PERMISSIONS_STATUS)
        //权限列表未操作 -> 进入权限列表
        if (permissionStatus == 0){
            showGombeCreditPermissionsPage()
            return
        }
        //是否是广告渠道
        val isAdSource = GombeCreditSharedHelper.takeGombeCreditSharedBoolean(GombeCreditSharedKey.GOMBECREDIT_IS_ADSOURCE)
        //广告渠道 && 权限列表未同意 -> 进入权限列表
        if (isAdSource && permissionStatus == -1){
            showGombeCreditPermissionsPage()
            return
        }
        //广告渠道 && 未同意sms权限 -> 进入权限列表
        if (isAdSource && !EasyPermissions.hasPermissions(requireContext(), Manifest.permission.READ_SMS)){
            showGombeCreditPermissionsPage()
            return
        }

        //已同意权限列表 && 已同意SMS权限 -> 上报设备数据
        if (permissionStatus == 1 && EasyPermissions.hasPermissions(requireContext(), Manifest.permission.READ_SMS)){
            //上报所有设备数据
            publishEventData(GombeCreditEventData(GombeCreditEventData.TYPE.GOMBECREDIT_SYC_ALL_DEVICE))
        }

        // 进件信息未完成
        if (GombeCreditProcessHelper.takeGombeCreditStepList().size > 0){
            showGombeCreditProcessStepsPage()
            return
        }

        //权限已全部同意 && 进件信息已完成 - 申贷试算页面
        showGombeCreditApplyPage()
    }

    /**
     * 进入权限列表页面
     */
    private fun showGombeCreditPermissionsPage(){
        limitData?.let {
            val limitAmount = BigDecimal(it.optString("amount")).stripTrailingZeros().toPlainString()
            val intent = Intent(context, ActGombeCreditPermissions::class.java)
            intent.putExtra("amount", limitAmount)
            permissionResultLauncher.launch(intent)
        }
    }

    /**
     * 进入填写进件信息页面
     */
    private fun showGombeCreditProcessStepsPage(){
        limitData?.let {
            val limitAmount = BigDecimal(it.optString("amount")).stripTrailingZeros().toPlainString()
            ActGombeCreditProcessSteps.start(requireContext(),limitAmount)
        }
    }

    /**
     * 进入申贷页面
     */
    private fun showGombeCreditApplyPage(){
        ActGombeCreditApply.start(requireContext())
    }

    /**
     * 额度增加提示
     */
    private fun showGombeCreditLimitIncreasedDialog(data: JSONObject){
        val dialog = DilaogGombeCreditLimitIncreased(requireContext(),data.optString("product"),object : DilaogGombeCreditLimitIncreased.IDialogCallback{
            override fun onClick(view: View?) {
                //申请
                _binding?.btnApplyNow?.callOnClick()
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
        dialog.showGombeCreditLimitIncreasedData(data)
    }

    override fun onGombeCreditPublishEvent(event: GombeCreditEventData) {
        super.onGombeCreditPublishEvent(event)
        when (event.eventType) {
            GombeCreditEventData.TYPE.GOMBECREDIT_DATA_REFRESH,
            GombeCreditEventData.TYPE.GOMBECREDIT_PROCESS_REFRESHED -> { //刷新流程完成
                //待还款
                val isRepay = GombeCreditProcessHelper.isGombeCreditRepay()
                //审核中 || 放款中 || 已拒绝
                val isReviewing = GombeCreditProcessHelper.isGombeCreditReviewing()
                val isDisbursing = GombeCreditProcessHelper.isGombeCreditDisbursing()
                val isRejected = GombeCreditProcessHelper.isGombeCreditRejected()
                if (isRepay or isReviewing or isDisbursing or isRejected){
                    return
                }

                loadGombeCreditHomeLimitAction()
                loadGombeCreditLimitIncreasedAction()
            }

            GombeCreditEventData.TYPE.GOMBECREDIT_ORDER_REFRESHED -> {//订单刷新完成
            }

            GombeCreditEventData.TYPE.GOMBECREDIT_SHOW_AUTHENTICATION -> {
            }
            GombeCreditEventData.TYPE.GOMBECREDIT_NET_ERROR -> {//网络加载失败
                hideGombeCreditLoading()
            }
            else -> {

            }
        }
    }

    /**
     * 获取显示额度
     */
    private fun loadGombeCreditHomeLimitAction(){
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_LIMIT_PATH)
            }
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                val limitArray = obj?.optJSONArray("limit")
                limitArray?.let {
                    if (it.length() > 0){
                        val limitObj = it.optJSONObject(0)
                        showGombeCreditHomeLimit(limitObj)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    /**
     * 加载产品额度是否增加
     */
    private fun loadGombeCreditLimitIncreasedAction(){
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_LIMIT_UP_PATH)
            }
        //todo 测试提额dialog
//        params.put("selectAmount","2000")
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    if (it.optString("openFlag") == "YES"){
                        showGombeCreditLimitIncreasedDialog(it)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    override fun hideGombeCreditLoading() {
        super.hideGombeCreditLoading()
        _binding?.homePageRefreshLayout?.isRefreshing = false
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.HOME_END)
    }
}